/*
 * @Autor: Shihh
 * @Description: 
 * @Version: 1.0
 * @Date: 2020-05-11 15:23:15
 */

var express = require('express');
var image_router = express.Router();
var db = require('../../models');
const Op = require('sequelize').Op;
const sequelize = require('sequelize');
var comm = require('../../comm')

/**
 * @author: Shihh
 * @description: 管理端分页 并带出图片拥有的tagid tagname
 * @param {type} 
 * @return: 
 */


image_router.post('/getimglist', async (req, res) => {
    var [page = 1, pagesize = 30,] = [req.body.page, req.body.pagesize]
    let condition = {
        "pagesize": pagesize,
        "page": page
    }
    let imgList = await db.images.getListTags(condition)
    for (let r of imgList.rows) {
        if (r.tagIds) {
            let tagArr = r.tagIds.split(',')
            let labelArr = []
            for (let item of tagArr) {
                await new Promise(resolve => {
                    comm.redis.get(item, function (err, data) {
                        labelArr.push(data);
                        resolve()
                    })
                })
            }
            let label = labelArr.toString()
            r['label'] = label
        }
        r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
        delete r.oss_prepath
        delete r.prefix_path
    }

    res.json(imgList)

})

image_router.post('/updatePicture', async (req, res) => {
    let status = await db.images.updateImage(req.body)
    res.json(status)

}),

    /**
     * @author: Shihh
     * @description: 图片分组查询
     * @param {type} 
     * @return: 
     */
    image_router.post('/searchImg', async (req, res) => {
        var searchData = req.body.searchData
        var pageSet = req.body.pageSet
        var [page = 1, pagesize = 12] = [pageSet.page, pageSet.pagesize]
        let whereData = {}
        if (searchData.category) {
            whereData['category'] = searchData.category
        }

        if (searchData.status != null && searchData.status !== '') {

            whereData['is_enable'] = searchData.status
        }
        if (searchData.id) {
            var Ids = searchData.id.split(',')
            if (Ids.length > 1) {
                whereData['id'] = {
                    [Op.in]: Ids
                }
            } else {
                whereData['id'] = {
                    [Op.like]: `%${searchData.id}%`
                }
            }

        }
        if (searchData.img_designer) {
            whereData['img_designer'] = {
                [Op.like]: `%${searchData.img_designer}%`
            }
        }
        if (searchData.image_name) {
            whereData['img_name'] = {
                [Op.like]: `%${searchData.image_name}%`
            }
        }
        if (searchData.tagId) {
            let result = await db.tagImage.findOne(
                {
                    attributes: [[sequelize.fn('group_concat', sequelize.col('image_id')), 'ids']],
                    where: { 'tag_id': searchData.tagId },
                    raw: true
                })
            var idArr = result.ids.split(',')
            if (searchData.id) {
                var imageIds = searchData.id.split(',')
                if (imageIds.length > 1) {
                    let finalArr = idArr.filter(v => imageIds.includes(v))
                    whereData['id'] = {
                        [Op.in]: finalArr
                    }
                } else {
                    whereData['id'] = {
                        [Op.and]: {
                            [Op.in]: idArr,
                            [Op.like]: `%${searchData.id}%`
                        }
                    }
                }
            } else {
                whereData['id'] = {
                    [Op.in]: idArr
                }
            }
        }
        let imgList = await db.images.findAndCountAll({
            where: whereData,
            raw: true,
            attributes: ['*'],
            offset: pagesize * (page - 1),
            limit: parseInt(pagesize),
        })
        for (let r of imgList.rows) {
            if (r.tagIds) {
                let tagArr = r.tagIds.split(',')
                let labelArr = []

                for (let item of tagArr) {
                    await new Promise(resolve => {
                        comm.redis.get(item, function (err, data) {
                            labelArr.push({
                                id: item,
                                name: data
                            });
                            resolve()
                        })
                    })
                }
                r['label'] = labelArr
            }

            var categoryArr = []
            await new Promise(resolve => {
                comm.redis.hget('category', r.category, async function (err, data) {
                    let result = JSON.parse(data)
                    if (result.parentid !== 0) {
                        await comm.redis.hget('category', result.parentid, function (err, data) {
                            let p_result = JSON.parse(data)
                            categoryArr.push(p_result.name)
                            categoryArr.push(result.name)
                            r.category = categoryArr.toString()
                        })
                    } else {
                        categoryArr.push(result.name)
                        r.category = categoryArr.toString()

                    }
                    resolve()
                })

            })
            delete r.tagIds
            r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
            delete r.oss_prepath
            delete r.prefix_path
        }
        res.json(imgList)
    }),

    /**
     * @author: Shihh
     * @description: 删除单个图片单个标签
     * @param {type} 
     * @return: 
     */
    image_router.post('/deleteTag', async (req, res) => {
        var id = req.body.id;
        var tag_id = req.body.tag_id;
        let result = await db.sequelize.transaction(t => {
            return db.tagImage.destroy(
                {
                    where: {
                        "image_id": id,
                        "tag_id": tag_id
                    },
                    transaction: t
                }).then(() => {
                    return db.tagImage.findOne({
                        attributes: [
                            ['image_id', 'id'],
                            [sequelize.fn('group_concat', sequelize.col('tag_id')), 'tagIds']
                        ],
                        raw: true,
                        where: {
                            'image_id': id
                        },
                        transaction: t
                    }).then(img => {
                        return db.images.update(
                            { tagIds: img.tagIds },
                            {
                                where: {
                                    "id": id
                                },
                                transaction: t
                            }
                        ).then(() => {
                            return true
                        }).catch(err => {
                            console.log(err)
                        })
                    })
                }).catch(err => {
                    console.log(err)
                })
        }).then(res => {
            return true
        }).catch(err => {
            console.log(err)
        })
        res.json(result)
    })


/**
 * @author: xgq
 * @description: 
 * @param {type} 
 * @return: 
 */
image_router.post('/getImgCount', async (req, res) => {
    let result = await db.images.count()
    res.json(result)
})


/**
 * @author: xgq
 * @description: 单个图片下架
 * @param {type} 
 * @return: 
 */
image_router.get('/singleOff', async (req, res) => {
    var pars = {
        is_enable: 1,
        id: req.query.id
    }
    let result = await db.images.update_is_enable(pars)
    res.json(result)
})

/**
 * @author: xgq
 * @description:单个图片上架 
 * @param {type} 
 * @return: 
 */
image_router.get('/singleUp', async (req, res) => {
    var pars = {
        is_enable: 0,
        id: req.query.id
    }
    let result = await db.images.update_is_enable(pars)
    res.json(result)
})

/**
 * @author: xgq
 * @description: 批量下架
 * @param {type} 
 * @return: 
 */
image_router.post('/imagesDown', async (req, res) => {
    var ids = req.body.ids;
    var status = 1
    var pars = {
        ids,
        status
    }
    let result = await db.images.imagesUpORDown(pars)
    res.json(result)
})
/**
 * @author: xgq
 * @description: 批量上架
 * @param {type} 
 * @return: 
 */
image_router.post('/imagesUp', async (req, res) => {
    var ids = req.body.ids;
    var status = 0
    var pars = {
        ids,
        status
    }
    let result = await db.images.imagesUpORDown(pars)
    res.json(result)
})


/**
 * @author: Shihh
 * @description: 批量设置图片分类
 * @param {type} 
 * @return: 
 */
image_router.post('/batchCategory', async (req, res) => {
    var ids = req.body.ids;
    var categoryId = req.body.categoryId
    let category = {}
    category = JSON.parse(await comm.redhget('category', categoryId))
    if (Object.keys(category).length === 0) {
        category = await db.category.findByPk(categoryId, { raw: true })
    }
    await db.images.update({
        category: categoryId, e_category: category.code
    }, {
        where: {
            "id": {
                [Op.in]: ids
            },
        }
    }).then(re => {
        res.json({ code: 200, msg: "设置成功" })
    }).catch(err => {
        console.log(err)
        res.json({ code: 400, msg: "设置失败" })

    })
})
//   // 客户端首页获取最新图片
//   async fornt_getNew(req, res) {
//     var [page = 1, pageSize = 12, ] = [req.body.page, req.body.pageSize]
//     let condition = {
//       "pagesize": pageSize,
//       "page": page
//     }
//     var imgList = await db.images.fornt_getNew(condition)
//     for (let r of imgList.rows) {
//       r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
//       delete r.oss_prepath
//       delete r.prefix_path
//     }
//     imgList.code = 200

//     res.json(imgList)
//   },
//   // 客户端首页获取TopList排行图片
//   async fornt_getTopList(req, res) {
//     var [page = 1, pagesize = 12, userid] = [req.body.page, req.body.pageSize, req.body.userid]
//     let condition = {
//       "pagesize": pagesize,
//       "page": page
//     }
//     var imgList = await db.images.fornt_getMostDown(condition)
//     if (userid !== '' && userid !== null) {
//       for (var o of imgList.rows) {
//         let pars = {};
//         pars.image_id = o.id
//         pars.uid = userid
//         let collectList = await m_userImgModel.checkUserCollect(pars);
//         if (collectList.length > 0) {
//           o.isCollect = true
//         } else {
//           o.isCollect = false
//         }
//       }
//     } else {
//       for (var y of imgList.rows) {
//         y['isCollect'] = '';
//       }
//     }
//     for (let r of imgList.rows) {
//       r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
//       delete r.oss_prepath
//       delete r.prefix_path
//     }
//     imgList.code = 200
//     res.json(imgList)
//   },
//   //  客户端获取首页热门Top排行图片列表
//   async fornt_getTopHotImageList(req, res) {
//     var [page = 1, pagesize = 12, userid] = [req.body.page, req.body.pageSize, req.body.userid]
//     let condition = {
//       "pagesize": pagesize,
//       "page": page
//     }
//     var imgList = await db.images.fornt_getMostHot(condition)
//     if (userid !== '' && userid !== null) {
//       for (var o of imgList.rows) {
//         let pars = {};
//         pars.image_id = o.id
//         pars.uid = userid
//         let collectList = await m_userImgModel.checkUserCollect(pars);
//         if (collectList.length > 0) {
//           o.isCollect = true
//         } else {
//           o.isCollect = false
//         }
//       }
//     } else {
//       for (var y of imgList.rows) {
//         y['isCollect'] = '';
//       }
//     }
//     for (let r of imgList.rows) {
//       r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
//       delete r.oss_prepath
//       delete r.prefix_path
//     }
//     imgList.code = 200
//     res.json(imgList)
//   },


//   // 前台页面获取图片列表
//   async fornt_getImgList(req, res) {
//     var [page = 1, pagesize = 30, ] = [req.body.page, req.body.pagesize]
//     let condition = {
//       "pagesize": pagesize,
//       "page": page
//     }
//     var imgList = []

//     var queryData = req.body.queryData
//     if (queryData != undefined) {

//       if (queryData.category_id != undefined && queryData.category_id != null) {
//         condition.category_id = queryData.category_id
//       }
//       if (queryData.tag_id != undefined && queryData.tag_id != null) {
//         condition.tag_id = queryData.tag_id
//       }
//       if (queryData.getNew != undefined && queryData.getNew != null) {
//         condition.order = [
//           ['create_time', 'DESC']
//         ]
//       }
//       if (queryData.topic_id != undefined && queryData.topic_id != null) {
//         // 专题热度值+1
//         let add_topic_wacth_num = await m_topicModel.update({
//           watch_num: db.images.sequelize.literal('watch_num + 1')
//         }, {
//           'where': {
//             'id': queryData.topic_id
//           }
//         })
//         condition.topic_id = queryData.topic_id
//       }
//     }
//     imgList = await db.images.fornt_getImgList(condition)

//     if (queryData.keyWords != undefined && queryData.keyWords != null) {
//       condition.keyWords = queryData.keyWords
//       imgList = await db.images.fornt_seachImgList(condition)
//     }
//     for (let r of imgList.rows) {
//       r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
//       delete r.oss_prepath
//       delete r.prefix_path
//     }
//     imgList.code = 200
//     res.json(imgList)
//   },



//   // 客户端下载图片,更新图片下载量
//   async fornt_add_download_counts(req, res) {
//     // var pars = req.body;
//     let user_id = req.body.uid;
//     let img_id = req.body.image_id
//     var queryData = await db.images.sequelize.transaction(t => {
//       return db.images.update({
//           download_counts: db.images.sequelize.literal('download_counts + 1')
//         }, {
//           'where': {
//             'id': img_id
//           }
//         }, {
//           transaction: t
//         })
//         .then(user => {
//           return m_userImgModel.create({
//             img_id,
//             user_id,
//             operate: 0
//           }, {
//             transaction: t
//           })
//         })
//     });
//     res.json({
//       code: 1,
//       msg: '已更新下载数',
//       data: queryData
//     })
//   },
//   // 客户端点赞图片
//   async fornt_likePicture(req, res) {
//     var pars = req.body;
//     let user_id = req.body.uid;
//     let img_id = req.body.image_id

//     var result = await m_userImgModel.checkUserLike(pars);
//     if (result.length > 0) {
//       //删除标签与图片的关系
//       let r = await db.images.sequelize.transaction(t => {
//         return m_userImgModel.destroy({
//           where: {
//             "img_id": img_id,
//             "user_id": user_id,
//             "operate": 1
//           }
//         }, {
//           transaction: t
//         }).then(user => {
//           return db.images.update({
//             like_num: db.images.sequelize.literal('like_num - 1')
//           }, {
//             where: {
//               "id": img_id,
//             }
//           }, {
//             transaction: t
//           })
//         });
//       }).then(result => {
//         return result
//       }).catch(err => {
//         return null
//       })
//       res.json({
//         code: -1,
//         msg: '已经取消点赞',
//         data: r
//       })
//     } else {
//       var queryData = await db.images.sequelize.transaction(t => {
//         return db.images.update({
//             like_num: db.images.sequelize.literal('like_num + 1')
//           }, {
//             'where': {
//               'id': img_id
//             }
//           }, {
//             transaction: t
//           })
//           .then(user => {
//             return m_userImgModel.create({
//               img_id,
//               user_id,
//               operate: 1
//             }, {
//               transaction: t
//             })
//           })
//       });
//       res.json({
//         code: 1,
//         msg: '点赞成功',
//         data: queryData
//       })
//     }




module.exports = image_router